package com.example.administrator.szb.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.administrator.szb.R;
import com.example.administrator.szb.adapter.BaseAdapter;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.bean.IndexBean;
import com.example.administrator.szb.bean.TWBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.Toasts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by D N on 2017/11/10.
 */

public class AskNewActivity extends BaseActivity {
    @Bind(R.id.ask_new_edit_title)
    EditText askNewEditTitle;
    @Bind(R.id.ask_new_ll_title)
    LinearLayout askNewLlTitle;
    @Bind(R.id.ask_new_edit_wtbc)
    EditText askNewEditWtbc;
    @Bind(R.id.ask_new_ll_wtbc)
    LinearLayout askNewLlWtbc;
    @Bind(R.id.ask_new_recyclerview)
    RecyclerView askNewRecyclerview;
    BaseAdapter<IndexBean.DataBean.BusinessBean> adapter;
    IndexBean.DataBean businessBean;

    int users_id;

    ArrayList<String> info_all = new ArrayList<>();
    Map<Integer,String> info_id = new HashMap<Integer, String>(){
        @Override
        public String toString() {
            String info = "";
            Iterator<Integer> it = info_id.keySet().iterator();
            while (it.hasNext()){
                info = info + info_id.get(it.next()) +",";
            }
            return info;
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ask_new_activity);
        ButterKnife.bind(this);
        SampleApplicationLike.getActivitiesInstance().add(this);
        businessBean = SampleApplicationLike.getIndexBeanInstance().getData();
        if (businessBean==null){
            finish();
        }else {
            initToolbarThree(R.id.ask_new_toolbar_include, "提问", "发布", new Callback() {
                @Override
                public void doSomeThing() {


                    if (SampleApplicationLike.getUserloginInstance().getId() == 0){
                        startActivity(new Intent(AskNewActivity.this,LoginNewActivity_two.class));
                    }else{
                        requestData();
                    }
                }
            });

            users_id = JGXQActivity.gwjgBean.getData().getUsers_id();

            initRecyclerView();
        }

    }

    private void requestData() {
        boolean flag = checkInfo();
        if (flag){
            doFb();
        }
    }

    private void doFb() {
       //DialogUtil.showProgressbar(this,R.layout.ask_new_activity);
        ((TextView) toolbar.findViewById(R.id.toolbar_three_text_subtitle)).setEnabled(false);
        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("id", SampleApplicationLike.getUserloginInstance().getId() + "");
        map.put("users_id", users_id+"");
        map.put("content", info_all.get(1));
        map.put("title", info_all.get(0));
        map.put("business_id", info_all.get(2));
        map.put("refer_id", "0");//0代表是提问，其他id代表回答
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, TWBean.class, URLAddress.URLBASE + URLAddress.URL_TW_HD, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                ((TextView) toolbar.findViewById(R.id.toolbar_three_text_subtitle)).setEnabled(true);
                TWBean twBean = (TWBean) response;
                if (twBean.getResult() == 1) {
//                    DialogUtil.showSimpleDialog(AskActivity.this,"提问成功");
                    //DialogUtil.loading.dissmiss();
                    Toasts.show(AskNewActivity.this, "提问成功", Toast.LENGTH_SHORT);
                    finish();
                } else {
                    //DialogUtil.loading.dissmiss();
                    Toasts.show(AskNewActivity.this, "" + twBean.getErr_msg(), Toast.LENGTH_SHORT);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                ((TextView) toolbar.findViewById(R.id.toolbar_three_text_subtitle)).setEnabled(true);
                //DialogUtil.loading.dissmiss();
                Toasts.show(AskNewActivity.this, "" + error.toString(), Toast.LENGTH_SHORT);
            }
        });
    }

    private boolean checkInfo() {
        getInfo();
        if (TextUtils.isEmpty(info_all.get(0))) {
            Toasts.show(this, "请输入标题", Toast.LENGTH_SHORT);
        } else if (TextUtils.isEmpty(info_all.get(1))) {
            Toasts.show(this, "请输入内容", Toast.LENGTH_SHORT);
        } else if (TextUtils.isEmpty(info_all.get(2)) || info_all.get(2).equals(",")) {
            Toasts.show(this, "请选择业务类型", Toast.LENGTH_SHORT);
        } else {
            return true;
        }
        return false;
    }

    private void initRecyclerView() {
        askNewRecyclerview.setLayoutManager(new GridLayoutManager(this, 4));
        adapter = new BaseAdapter<IndexBean.DataBean.BusinessBean>(this, businessBean.getBusiness()) {
            @Override
            public void convert(final int position, BaseViewHolder holder, final IndexBean.DataBean.BusinessBean businessBean) {
                ((CheckBox) holder.getView(R.id.xzyw_radiobutton_gpzy)).setText(businessBean.getTitle());
                if (businessBean.getIsChoose() == 0) {
                    ((CheckBox) holder.getView(R.id.xzyw_radiobutton_gpzy)).setChecked(false);
                }

                ((CheckBox) ((CheckBox) holder.getView(R.id.xzyw_radiobutton_gpzy))).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        if (b){
                            if (info_id.size() > 3) {
                                Toasts.show(AskNewActivity.this, "最多选择四项业务", Toast.LENGTH_SHORT);
                                compoundButton.setChecked(false);
                                return;
                            }

                            info_id.put(position,businessBean.getId()+"");
                        }else{
                            info_id.remove(position);
                        }
                    }
                });
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_xzyw_item;
            }
        };
        askNewRecyclerview.setAdapter(adapter);
    }

    @OnClick({R.id.ask_new_ll_title, R.id.ask_new_ll_wtbc})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ask_new_ll_title:
                askNewEditTitle.requestFocus();
                InputMethodManager imm = (InputMethodManager) askNewEditTitle.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                break;
            case R.id.ask_new_ll_wtbc:
                askNewEditWtbc.requestFocus();
                InputMethodManager imm_wtbc = (InputMethodManager) askNewEditWtbc.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm_wtbc.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                break;
        }
    }

    public void getInfo() {
        info_all.clear();
        info_all.add(askNewEditTitle.getText().toString().trim());
        info_all.add(askNewEditWtbc.getText().toString().trim());
        info_all.add(info_id.toString());
    }
}
